const pageStack = getCurrentPages()
Page({
  onLoad(){
    const app = getApp()
    this.setData({
      ...app.userProfile
    })
  },
  getUserNickname(ev){
    this.updateUserNickname(ev.detail.value)
  },
  async updateUserNickname(nickName){
    if (nickName==''){
      return
    }
    const {code} = await wx.http.put('/userInfo',{nickName})
    if (code!==10000){
      return wx.utils.toast('更新用户昵称失败')
    }
    pageStack[0].setData({
      nickName: nickName,
    })
    const app = getApp()
    app.userProfile.nickName = nickName
  },
  getUserAvatar(ev){
    this.updateAvatar(ev.detail.avatarUrl)
  },
  updateAvatar(avatar){
    wx.uploadFile({
      url: wx.http.baseURL+'/upload',
      filePath: avatar,
      name:'file',
      header:{
        Authorization:'Bearer ' + getApp().token
      },
      formData:{type:'avatar'},
      success:(result)=>{
        const data = JSON.parse(result.data)
        console.log(data)
        if(data.code!==10000){
          return wx.utils.toast('上传图像失败！')
        }
        pageStack[0].setData({
          avatar:data.data.url
        })
        const app = getApp()
        app.userProfile.avatar = data.data.url
        this.setData({avatar:data.data.url})
      }
    })
  }
})